<?php
namespace app\modules\v1\controllers;
use Yii;
use yii\rest\ActiveController;
use yii\web\Response;
use app\modules\v1\models\MerchantWeixin;
use app\modules\v1\models\MerchantBillDetails;
use app\modules\v1\models\Merchant;
use yii\base\Exception;
use app\modules\v1\models\Kameng;
use app\modules\v1\models\Merchantinfocard;

class XyfpaymentController extends ActiveController
{
	
    public $modelClass = 'app\modules\v1\models\xyfpayment';
    
    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['update'], $actions['create'], $actions['delete'], $actions['view']);
        return $actions;
    }

    public function actionCreate()
    {
    	$res = array();
    	if(Yii::$app->request->isPost){
    		$openid  		= isset(Yii::$app->request->post()['openid'])?trim(Yii::$app->request->post()['openid']):'';
    		$bill_total  	= isset(Yii::$app->request->post()['bill_total'])?trim(Yii::$app->request->post()['bill_total']):0;
    		$bill_type  	= isset(Yii::$app->request->post()['bill_type'])?trim(Yii::$app->request->post()['bill_type']):'';
    		$bill_type_arr 	= array(1,2);
    		
    		if($bill_type == 1){
    			$res['code'] 		= '10402';
    			$res['msg']  		= '暂不支持微信支付，换个扫码方式吧';
    			$response			= Yii::$app->response;
    			$response->format	= Response::FORMAT_JSON;
    			$response->data		= $res;
    			return $response;
    			exit;
    		}
    		
    		if(empty($bill_type) || !in_array($bill_type, $bill_type_arr)){
    			$res['code'] 		= '10402';
    			$res['msg']  		= '支付类型错误';
    			$response			= Yii::$app->response;
    			$response->format	= Response::FORMAT_JSON;
    			$response->data		= $res;
    			return $response;
    			exit;
    		}

    		if($bill_total<3){
    			$res['code'] 		= '10402';
    			$res['msg']  		= '最低限额为3';
    			$response			= Yii::$app->response;
    			$response->format	= Response::FORMAT_JSON;
    			$response->data		= $res;
    			return $response;
    			exit;
    		}
    		if(empty($openid)){
    			$res['code'] 		= '10402';
    			$res['msg']  		= '资料审核中';
    			$response=Yii::$app->response;
    			$response->format	=Response::FORMAT_JSON;
    			$response->data		=$res;
    			return $response;
    			exit;
    		}
    		$weixininfo  = MerchantWeixin::findByOpenid($openid);
    		if(!empty($weixininfo)){
    			$merchant1 		= Merchant::findOne($weixininfo->merchant_id);
    			//$arr_in			= array(6,8);//6：系统审核成功 ； 8：只开通微信支付宝，不支持信用付
    			//if(!empty($merchant1) && in_array($merchant1->check_status, $arr_in)){
    			if(!empty($merchant1) && $merchant1->check_status_jinjian == 3){ //java后台好了，改成上面的
    				$cardinfo23	= Merchantinfocard::findOne(['merchant_id'=>$weixininfo->merchant_id]);
    				
    				//单笔限额，单日限额处理
    				$max_amount 	 = $cardinfo23->signle_time_amount;
    				$day_max_amount  = $cardinfo23->signle_day_amount;
    				$today      	 = date('Y-m-d');
    				$query_day  	 = "SELECT SUM(money) as a  
    					FROM `merchant_bill_details` 
    					WHERE merchant_id='{$weixininfo->merchant_id}' AND pay_type ='2' AND date_time >= '{$today}'";
    				$connection 	 = Yii::$app->db;
    				$command1 		 = $connection->createCommand($query_day)->queryOne();
    				$user_day_amount = (string)$command1['a'];
    				if(($user_day_amount+$bill_total)>$day_max_amount){
    					$res['code'] 		= '10402';
    					$res['msg']  		= '您已超出单日最大交易限额';
    					$response			= Yii::$app->response;
    					$response->format	= Response::FORMAT_JSON;
    					$response->data		= $res;
    					return $response;
    					exit;
    				}
    				if($bill_total>$max_amount){
    					$res['code'] 		= '10402';
    					$res['msg']  		= '您已超出单笔最大交易限额'.$max_amount;
    					$response			= Yii::$app->response;
    					$response->format	= Response::FORMAT_JSON;
    					$response->data		= $res;
    					return $response;
    					exit;
    				}
    				
    				$tr = Yii::$app->db->beginTransaction();
    				try {
    					//调用进件下单接口，成功保存数据到detail表 ，支付宝，微信下单
    					$order_id 	 = (string)(Kameng::MindateNow().$weixininfo->merchant_id.rand(10, 99));
    					$merchant_id = $weixininfo->merchant_id;
    					//查询微信 t0 , t1     支付宝 t0 ,t1
    					$wxT0Fee		=  Yii::$app->params['wx_rates'];
    					$alipayT0Fee 	=  Yii::$app->params['zfb_rates'];

    					
    					if($bill_type == 1){
    						//微信
    						$counter_fee = $wxT0Fee*$bill_total;
    						$trxType	 = 'WX_SCANCODE_JSAPI';
    						$goodsName   = 'wxzf';
    					}else{
    						//支付宝
    						$counter_fee = $alipayT0Fee*$bill_total;
    						$trxType	 = 'Alipay_SCANCODE';
    						$goodsName   = 'zfbzf';
    					}
    					
    					
    					$deskey   		= $merchant1->des_key;  	//进件成功返回的deskkey
    					$signkey  		= $merchant1->sign_key; 	//进件成功返回的值
    					$merchantNo 	= $merchant1->vnion_merchant_no; 	
    					$idCardNo 		= $merchant1->identity_card;		//身份证号码
    					$payerName		= $merchant1->merchant_real_name;	//姓名
    					$cardinfo		= Merchantinfocard::findOne(['merchant_id'=>$weixininfo->merchant_id,'state'=>1,'is_bind'=>1]);
    					if(empty($cardinfo)){
    						$res['code'] 		= '10400';
    						$res['msg']  		= '用户银行卡信息不完整';
    						$response			= Yii::$app->response;
    						$response->format	= Response::FORMAT_JSON;
    						$response->data		= $res;
    						return $response;
    					}
    				 	$toibkn	  	= $cardinfo->bank_code;             //收款行联行号
    					$cardNo   	= $cardinfo->account_no;		    //银行卡号 
    					$map  = array(
    							'trxType'		=> $trxType,
    							'merchantNo'	=> $merchantNo,
    							'orderNum'		=> $order_id,
    							'amount'		=> $bill_total,
    							'goodsName'		=> $goodsName,
    							'callbackUrl'	=> '',
    							'orderIp'		=> '192.168.15.60',
    							'toibkn'		=> $toibkn,   			
    							'cardNo'		=> $cardNo,         	
    							'idCardNo'		=> $idCardNo, 		
    							'payerName'		=> $payerName,   					
    							'encrypt'		=> 'T0',
    							'signkey'		=> $signkey
    					); 

    					if ($bill_type == 1){ //微信
    						$res_order = Kameng::OrderPost($map,$deskey);
    						$res_order = json_decode($res_order);
    						if(!empty($res_order) && isset($res_order->retCode) && $res_order->retCode == '1000'){
    							$merchant3  = new MerchantBillDetails();
    							$merchant3->merchant_id = $merchant_id;
    							$merchant3->date_time 	= date("Y-m-d H:i:s",time()+8*3600);
    							$merchant3->status 		= 1;   			//0交易成功1交易失败
    							$merchant3->money 		= $bill_total;
    							$merchant3->order_id 	= $order_id;
    							$merchant3->counter_fee = $counter_fee; //手续费用
    							$merchant3->pay_type 	= $bill_type;   //付款方式 1微信收款 2支付宝收款 3信用付收款 4账户返现
    							$merchant3->bill_type 	= 1;        	//类型 1转入 2转出
    							$merchant3->km_retMsg	= $res_order->retMsg;
    							$merchant3->km_qrCode	= $res_order->qrCode;
    							$merchant3->save();
    							//收款金额<=免手续费金额，我们会把扣除的手续费返还到商户的信用付账户中.
    							if($bill_total <= ($merchant1->free_balance)){
    								$merchant4  = new MerchantBillDetails();
    								$merchant4->merchant_id = $weixininfo->merchant_id;
    								$merchant4->date_time 	=  date("Y-m-d H:i:s",time()+8*3600);
    								$merchant4->status 		= 1;   			//0交易成功1交易失败
    								$merchant4->money 		= $counter_fee;
    								$merchant4->order_id 	= $order_id;
    								$merchant4->counter_fee = 0; 			//手续费用
    								$merchant4->pay_type 	= 4;   			//付款方式 1微信收款 2支付宝收款 3信用付收款 4账户返现
    								$merchant4->bill_type 	= 1;        	//类型 1转入 2转出
    								$merchant4->km_retMsg	= $res_order->retMsg;
    								$merchant4->km_qrCode	= $res_order->qrCode;
    								$merchant4->save();
    								$merchant1->free_balance = (($merchant1->free_balance) - $bill_total );
    								$merchant1->update();
    							}
    							$tr->commit();
    							$res['data']['qrCodeurl'] 	= $res_order->qrCode;
    							$res['code'] 			= '10000';
    							$res['msg']  			= '支付成功';
    							$response				= Yii::$app->response;
    							$response->format		= Response::FORMAT_JSON;
    							$response->data			= $res;
    							return $response;
    						}else{
    							$res['code'] 		= '10400';
    							$res['msg']  		= '支付失败';
    							$response			= Yii::$app->response;
    							$response->format	= Response::FORMAT_JSON;
    							$response->data		= $res;
    							return $response;
    						}
    					}else{
    						$res_order = Kameng::OrderPostZfb($map,$deskey);
    						$res_order = json_decode($res_order);
    						if(!empty($res_order) && isset($res_order->retCode) && $res_order->retCode == '1000'){
    							$merchant3  = new MerchantBillDetails();
    							$merchant3->merchant_id = $merchant_id;
    							$merchant3->date_time 	= date("Y-m-d H:i:s",time()+8*3600);
    							$merchant3->status 		= 1;   			//0交易成功1交易失败
    							$merchant3->money 		= $bill_total;
    							$merchant3->order_id 	= $order_id;
    							$merchant3->counter_fee = $counter_fee; //手续费用
    							$merchant3->pay_type 	= $bill_type;   //付款方式 1微信收款 2支付宝收款 3信用付收款 4账户返现
    							$merchant3->bill_type 	= 1;        	//类型 1转入 2转出
    							$merchant3->km_retMsg	= $res_order->retMsg;
    							$merchant3->km_qrCode	= $res_order->r9_qrCode;
    							$merchant3->save();
    							//收款金额<=免手续费金额，我们会把扣除的手续费返还到商户的信用付账户中.
    							if($bill_total <= ($merchant1->free_balance)){
    								$merchant4  = new MerchantBillDetails();
    								$merchant4->merchant_id = $weixininfo->merchant_id;
    								$merchant4->date_time 	=  date("Y-m-d H:i:s",time()+8*3600);
    								$merchant4->status 		= 1;   			//0交易成功1交易失败
    								$merchant4->money 		= $counter_fee;
    								$merchant4->order_id 	= $order_id;
    								$merchant4->counter_fee = 0; 			//手续费用
    								$merchant4->pay_type 	= 4;   			//付款方式 1微信收款 2支付宝收款 3信用付收款 4账户返现
    								$merchant4->bill_type 	= 1;        	//类型 1转入 2转出
    								$merchant4->km_retMsg	= $res_order->retMsg;
    								$merchant4->km_qrCode	= $res_order->r9_qrCode;
    								$merchant4->save();
    								$merchant1->free_balance = (($merchant1->free_balance) - $bill_total );
    								$merchant1->update();
    							}
    							$tr->commit();
    							$res['data']['qrCodeurl'] 	= $res_order->r9_qrCode;
    							$res['openid'] 				= $openid;
    							$res['code'] 				= '10000';
    							$res['msg']  				= '支付成功';
    							$response					= Yii::$app->response;
    							$response->format			= Response::FORMAT_JSON;
    							$response->data				= $res;
    							return $response;
    						}else{
    							$res['code'] 		= '10400';
    							$res['msg']  		= '支付失败';
    							$response			= Yii::$app->response;
    							$response->format	= Response::FORMAT_JSON;
    							$response->data		= $res;
    							return $response;
    						}
    					}	
    				} catch (Exception $e) {
    					$tr->rollBack();
    					$res['code'] 		= '10400';
    					$res['msg']  		= '支付失败-';
    					$response			= Yii::$app->response;
    					$response->format	= Response::FORMAT_JSON;
    					$response->data		= $res;
    					return $response;
    				}
    			}else{		
    				$res['code'] 		= '10402';
    				$res['msg']  		= '资料审核中--';
    				$response			= Yii::$app->response;
    				$response->format	= Response::FORMAT_JSON;
    				$response->data		= $res;
    				return $response;
    			}
    		}else{
    			$res['code'] 		= '10402';
    			$res['msg']  		= '资料审核中-';
    			$response			= Yii::$app->response;
    			$response->format	= Response::FORMAT_JSON;
    			$response->data		= $res;
    			return $response;
    		}
    	}else{
    		$res['code'] 		= '10402';
    		$res['msg']  		= '资料审核中';
    		$response			= Yii::$app->response;
	    	$response->format	= Response::FORMAT_JSON;
	    	$response->data		= $res;
	    	return $response;
    	}
        
    }

}